<template>
    <div>
        <el-card class="box-card">
             <el-card class="filter-card" style="margin-bottom: 20px;">
                <div class="filter-header">
                    <i class="el-icon-filter"></i>
                    <span>筛选条件</span>
                </div>
                <el-form :inline="true" :model="formInline" class="demo-form-inline">
                    <el-form-item>
                        <el-input 
                            @change="onSubmit" 
                            v-model="formInline.search" 
                            placeholder="搜索CIDR" 
                            prefix-icon="el-icon-search">
                        </el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-select 
                            v-model="formInline.deliveryCount" 
                            placeholder="按发货量筛选" 
                            clearable 
                            @change="onSubmit">
                            <el-option label="发货量 = 0" :value="0"></el-option>
                            <el-option label="发货量 > 100" :value="100"></el-option>
                            <el-option label="发货量 > 500" :value="500"></el-option>
                            <el-option label="发货量 > 1000" :value="1000"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-select 
                            v-model="formInline.excludeAcl" 
                            placeholder="按ACL筛选" 
                            clearable 
                            @change="onSubmit">
                            <el-option
                                v-for="item in aclsList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-select 
                            v-model="formInline.serverFilter" 
                            placeholder="按引用筛选" 
                            clearable 
                            @change="onSubmit">
                            <el-option label="未被引用" value="unreferenced"></el-option>
                            <el-option
                                v-for="item in serverList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item class="filter-buttons">
                        <el-button @click="onSubmit" type="primary" icon="el-icon-search">搜索</el-button>
                        <el-button @click="resetFilter" icon="el-icon-refresh">重置</el-button>
                        <el-button @click="cleanUnusedCidr" type="danger" icon="el-icon-delete" :loading="cleanLoading">清理未使用CIDR</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
            <el-table 
                :data="tableData" 
                header-cell-class-name="table_header" 
                style="width: 100%"
                v-loading="tableLoading" 
                @sort-change="handleSortChange"
                :row-class-name="tableRowClassName"
                border
                stripe
                highlight-current-row
                class="data-table">
                <el-table-column align="center" label="ID" prop="id" sortable="custom" width="80"></el-table-column>
                <!-- <el-table-column align="center" label="id count" prop="id_count"></el-table-column> -->
                <el-table-column align="center" label="CIDR" prop="cidr" sortable="custom"></el-table-column>
                
                <el-table-column align="center" label="排除ACL" show-overflow-tooltip>
                    <template v-slot="{ row }">
                        <template>
                            <div class="acl-tags-container">
                                <el-tooltip 
                                    v-for="item in row.exclude_acl" 
                                    :key="item.id"
                                    :content="item.name" 
                                    placement="top"
                                    effect="light">
                                    <el-tag size="medium" class="acl-tag" type="info">{{ item.name }}</el-tag>
                                </el-tooltip>
                                <el-tag v-if="!row.exclude_acl || row.exclude_acl.length === 0" type="info" size="medium" class="acl-tag empty-tag">无</el-tag>
                            </div>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="发货量" prop="delivery_count" sortable="custom">
                    <template v-slot="{ row }">
                        <el-tag :type="getDeliveryCountType(row.delivery_count)" effect="plain" size="medium">
                            {{ row.delivery_count }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="引用服务器" show-overflow-tooltip>
                    <template v-slot="{ row }">
                        <div class="server-tags-container">
                            <el-tooltip 
                                v-for="serverId in row.server_ids" 
                                :key="serverId"
                                :content="getServerName(serverId)" 
                                placement="top"
                                effect="light">
                                <el-tag size="medium" class="server-tag" type="success">{{ getServerName(serverId) }}</el-tag>
                            </el-tooltip>
                            <el-tag v-if="!row.server_ids || row.server_ids.length === 0" type="info" size="medium" class="server-tag empty-tag">未被引用</el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="120">
                    <template v-slot="{ row }">
                        <el-button @click="handleEdit(row)" type="primary" size="mini" icon="el-icon-edit" circle></el-button>
                        <!-- <el-button @click="handleDelete(row, $index)" type="danger" size="mini" icon="el-icon-delete" circle></el-button> -->
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container">
                <el-pagination 
                    :current-page.sync="currentPage" 
                    :total="total" 
                    @current-change="handleCurrentChange"
                    :page-size="10"
                    layout="total, prev, pager, next, jumper"
                    background>
                </el-pagination>
            </div>
        </el-card>
        <el-dialog :visible.sync="dialogFormVisible" width="40%" :title="handleType === 'edit' ? '编辑CIDR' : '添加CIDR'" custom-class="cidr-dialog" :modal="false">
            <div class="dialog-content">
                <el-form :model="form" :rules="rules" label-width="100px" ref="ruleForm">
                    <el-form-item label="CIDR" prop="cidr">
                        <el-input v-model="form.cidr" disabled>
                            <template slot="prepend"><i class="el-icon-connection"></i></template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="IP数量" prop="ip_count">
                        <el-input v-model="form.cidr" disabled>
                            <template slot="prepend"><i class="el-icon-data-analysis"></i></template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="排除ACL" prop="exclude_acl">
                        <el-select 
                            multiple 
                            v-model="form.exclude_acl" 
                            style="width: 100%"
                            placeholder="请选择要排除的ACL"
                            filterable
                            collapse-tags>
                            <el-option
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                                v-for="item in aclsList">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item class="dialog-footer">
                        <el-button :loading="EditLoading" @click="handleSubmit" type="primary" icon="el-icon-check">保存</el-button>
                        <el-button :disabled="EditLoading" @click="dialogFormVisible = false" icon="el-icon-close">取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>
    </div>
</template>


<script>
import {getList, handle, add, cleanUnused} from "@/api/dashboard/CIDRList"
import {getList as getServeList} from "@/api/dashboard/acl"
import {getList as getServerList} from "@/api/dashboard/servers"

export default {
    data() {
        var validateacls = (rule, value, callback) => {
            if (value.length == 0) {
                callback(new Error('Please select acl'))
            } else {
                callback()
            }
        }
        return {
            formInline: {
                search: '',
                deliveryCount: '',
                excludeAcl: '',
                serverFilter: '',
                sortBy: '',
                sortOrder: ''
            },
            tableData: [],
            currentPage: 1,
            total: 0,
            tableLoading: false,
            dialogFormVisible: false,
            EditLoading: false,
            cleanLoading: false,
            // viewInfo: {}
            form: {
                cidr: '',
                ip_count: "",
                exclude_acl: []
            },
            handleType: "",
            aclsList: [],
            serverList: [],
            serverMap: {},
            formLoading: false
        }
    },
    mounted() {
        new this.$wow.WOW().init()
        this.getTableData()
        
        // 获取ACL列表
        getServeList({limit: 500, offset: 0}, res => {
            this.aclsList = res.data.data
        }, res => {
            this.$message.warning(res.msg)
        })
        
        // 获取服务器列表
        getServerList({limit: 500, offset: 0}, res => {
            this.serverList = res.data.data
            // 创建服务器ID到名称的映射
            this.serverMap = {}
            this.serverList.forEach(server => {
                this.serverMap[server.id] = server.name
            })
        }, res => {
            this.$message.warning(res.msg)
        })
    },
    methods: {
        refreshTableData() {
            this.getTableData()
        },

        getDeliveryCountType(count) {
            if (count > 1000) return 'danger';
            if (count > 500) return 'warning';
            if (count > 100) return 'success';
            return 'info';
        },
        tableRowClassName({row, rowIndex}) {
            if (row.delivery_count > 1000) {
                return 'high-delivery-row';
            }
            return '';
        },
        onSubmit() {
            this.currentPage = 1
            this.getTableData()
        },
        getServerName(serverId) {
            return this.serverMap[serverId] || `服务器 ${serverId}`
        },
        
        resetFilter() {
            this.formInline = {
                search: '',
                deliveryCount: '',
                excludeAcl: '',
                serverFilter: '',
                sortBy: this.formInline.sortBy,
                sortOrder: this.formInline.sortOrder
            }
            this.currentPage = 1
            this.getTableData()
        },
        handleSortChange({ prop, order }) {
            if (order === 'ascending') {
                this.formInline.sortOrder = 'asc'
            } else if (order === 'descending') {
                this.formInline.sortOrder = 'desc'
            } else {
                this.formInline.sortOrder = ''
            }
            this.formInline.sortBy = prop
            this.getTableData()
        },
        handleCurrentChange(val) {
            this.getTableData()
        },
        getTableData() {
            const offset = (this.currentPage - 1) * 10
            const param = {
                search: this.formInline.search,
                limit: 10,
                offset,
                sort_by: this.formInline.sortBy,
                sort_order: this.formInline.sortOrder
            }
            
            if (this.formInline.deliveryCount !== undefined && this.formInline.deliveryCount !== '') {
                if (this.formInline.deliveryCount === 0) {
                    param.delivery_count_exact = 0
                } else {
                    param.delivery_count_min = this.formInline.deliveryCount
                }
            }
            
            if (this.formInline.excludeAcl) {
                param.exclude_acl = this.formInline.excludeAcl
            }
            
            // 添加服务器引用筛选
            if (this.formInline.serverFilter) {
                if (this.formInline.serverFilter === 'unreferenced') {
                    param.unreferenced = true
                } else {
                    param.server_id = this.formInline.serverFilter
                }
            }
            
            this.tableLoading = true
            getList(param, (res) => {
                this.tableData = res.data.data
                this.total = res.data.total
                this.tableLoading = false
            })
        },
        handleEdit(row) {
            this.handleType = "edit"
            this.dialogFormVisible = true
            setTimeout(()=> {
                this.form = Object.assign({}, row);
                this.form.exclude_acl = row.exclude_acl.map(item => item.id);
            },0)
        },
        handleAdd() {
            this.handleType = "add"
            this.dialogFormVisible = true
        },
        handleSubmit() {
            this.$refs["ruleForm"].validate((valid) => {
                if (valid) {
                    this.EditLoading = true
                    if (this.handleType == "edit") {
                        const param = {...this.form}
                        // let arr = []
                        // param.exclude_acl.forEach(ele=> {
                        //     let obj = this.aclsList.find(item=> item.id == ele)
                        //     arr.push({name: obj.name, id:obj.id})
                        // })
                        handle({...param}, (res) => {
                            this.dialogFormVisible = false
                            this.EditLoading = false
                            this.$message.success("successfully")
                            this.getTableData()
                        }, (res) => {
                            this.$message.warning(res.msg)
                            this.EditLoading = false
                        })
                    } else {
                        const param = {...this.form}
                        add(param, (res) => {
                            this.dialogFormVisible = false
                            this.EditLoading = false
                            this.$message.success("successfully")
                            this.getTableData()
                        }, (res) => {
                            this.$message.warning(res.msg)
                            this.EditLoading = false
                        })
                    }
                } else {
                    return false
                }
            })
        },
        handleDelete(row, index) {
            this.$confirm(`Confirm deletion`, 'Delete ?', {
                confirmButtonText: 'YES',
                cancelButtonText: 'NO',
                type: 'warning'
            }).then(() => {
                handle(
                    "delete",
                    {id: row.id},
                    (res) => {
                        this.currentPage = this.currentPage === 1 ? this.currentPage : (this.tableData.length == 1 && index === 0) ? this.currentPage - 1 : this.currentPage
                        this.$message.success("successfully")
                        this.getTableData()
                    },
                )
            }).catch(() => {

            })
        },
        
        cleanUnusedCidr() {
            this.$confirm('确定要清理所有未被引用的CIDR记录吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.cleanLoading = true
                cleanUnused(
                    { include_soft_deleted: true },
                    (res) => {
                        const { results, deleted_count, cidr_details } = res.data
                        
                        // 创建结果消息
                        let message = `<div class="clean-result">
                            <p>成功清理了 <strong>${deleted_count}</strong> 条未被引用的CIDR记录</p>
                            <p>详细信息：</p>
                            <ul>
                                ${results.map(item => `<li>${item}</li>`).join('')}
                            </ul>
                        </div>`
                        
                        this.$notify({
                            title: '清理完成',
                            dangerouslyUseHTMLString: true,
                            message: message,
                            type: 'success',
                            duration: 10000,
                            position: 'bottom-right'
                        })
                        
                        this.cleanLoading = false
                        this.getTableData()
                    },
                    (res) => {
                        this.$message.error(res.msg || '清理失败')
                        this.cleanLoading = false
                    }
                )
            }).catch(() => {
                // 取消操作
            })
        }


    }
}
</script>

<style scoped lang="scss">
.box-card {
  margin: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
  
  :deep(.el-card) {
    border-radius: 8px;
    border: none;
    overflow: hidden;
  }

  .filter-card {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border: none;
    
    .filter-header {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      font-size: 16px;
      font-weight: 600;
      color: #606266;
      
      i {
        margin-right: 8px;
        font-size: 18px;
        color: #409EFF;
      }
    }
  }

  :deep(.el-form) {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }

  :deep(.el-form-item) {
    margin-right: 15px;
    margin-bottom: 10px;
  }
  
  .filter-buttons {
    margin-left: auto;
  }

  :deep(.el-input__inner), :deep(.el-select .el-input__inner) {
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    transition: all 0.3s;
    
    &:hover, &:focus {
      border-color: #409EFF;
    }
  }

  .data-table {
    margin-bottom: 20px;
    border-radius: 8px;
    overflow: hidden;
    
    :deep(.el-table__header-wrapper) {
      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 600;
        padding: 12px 0;
      }
    }
    
    :deep(.el-table__row) {
      transition: all 0.3s;
      
      &:hover {
        background-color: #f5f7fa;
      }
    }
    
    :deep(.high-delivery-row) {
      background-color: rgba(245, 108, 108, 0.1);
    }
  }

  :deep(.table_header) {
    background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
    color: #303133;
    font-weight: 600;
    padding: 12px 0;
  }
  
  .acl-tags-container,
  .server-tags-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 5px;
  }
  
  .acl-tag,
  .server-tag {
    margin: 2px;
    max-width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .empty-tag {
    opacity: 0.6;
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    margin-bottom: 10px;
    
    :deep(.el-pagination) {
      padding: 0;
      font-weight: normal;
      
      .btn-prev, .btn-next {
        background-color: #f5f7fa;
        color: #606266;
        border-radius: 4px;
      }
      
      .el-pager li {
        background-color: #f5f7fa;
        color: #606266;
        border-radius: 4px;
        margin: 0 3px;
        
        &.active {
          background-color: #409EFF;
          color: #fff;
        }
      }
    }
  }
}

/* 对话框样式改进 */
:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  
  .el-dialog__header {
    background-color: #f5f7fa;
    padding: 15px 20px;
    border-bottom: 1px solid #e4e7ed;
  }
  
  .el-dialog__body {
    padding: 20px;
  }
  
  .el-form-item__label {
    font-weight: 500;
  }
}

.cidr-dialog {
  .dialog-content {
    padding: 10px;
  }
  
  :deep(.el-input-group__prepend) {
    background-color: #f5f7fa;
    color: #409EFF;
  }
  
  :deep(.el-select .el-tag) {
    background-color: #ecf5ff;
    color: #409EFF;
    border-color: #d9ecff;
  }
  
  .dialog-footer {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

</style>